package cn.yuanqiao.web.controller.archive.formManage;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.io.IOException;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import cn.yuanqiao.archive.common.util.SplitArchiveList;
import cn.yuanqiao.common.utils.SnowflakeIdGenerator;
import cn.yuanqiao.common.utils.SecurityUtils;
import org.apache.commons.lang3.StringEscapeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import cn.yuanqiao.common.annotation.Log;
import cn.yuanqiao.common.enums.BusinessType;

import cn.yuanqiao.archive.formManage.formRule.domain.YqFormRule;
import cn.yuanqiao.archive.formManage.formRule.service.IYqFormRuleService;
import cn.yuanqiao.common.web.controller.BaseController;
import cn.yuanqiao.common.core.domain.AjaxResult;
import cn.yuanqiao.common.utils.poi.ExcelUtil;
import cn.yuanqiao.common.web.page.TableDataInfo;

/**
 * 分单规则Controller
 * 
 * @author yuanqiao
 * @date 2023-06-26
 */
@RestController
@RequestMapping("/archive/RULE")
public class YqFormRuleController extends BaseController
{
    @Autowired
    private IYqFormRuleService yqFormRuleService;


    @Autowired
    private SplitArchiveList splitArchiveList;

    /**
     * 查询分单规则列表
     */
    @PreAuthorize("@ss.hasPermi('archive:RULE:list')")
    @GetMapping("/list")
    public List<YqFormRule> list(YqFormRule yqFormRule)
    {
        //startPage();
        yqFormRule.setTenantCode(SecurityUtils.getTenantCode());
        if (yqFormRule.getType()==null){
            yqFormRule.setType("1");
        }
        List<YqFormRule> list = yqFormRuleService.selectYqFormRuleList(yqFormRule);
        return list;
    }

    /**
     * 查询分单规则列表
     */
    @PreAuthorize("@ss.hasPermi('archive:RULE:list')")
    @GetMapping("/listAndNoTenant")
    public List<YqFormRule> listAndNoTenant(YqFormRule yqFormRule)
    {
        //startPage();
        yqFormRule.setTenantCode(SecurityUtils.getTenantCode());
        if (yqFormRule.getType()==null){
            yqFormRule.setType("1");
        }
        List<YqFormRule> list = yqFormRuleService.listAndNoTenant(yqFormRule);
        return list;
    }

    /**
     * 查询分单规则列表
     */
    @PreAuthorize("@ss.hasPermi('archive:RULE:list')")
    @GetMapping("/ruleList")
    public List<YqFormRule>  ruleList(YqFormRule yqFormRule)
    {
        //startPage();
        yqFormRule.setTenantCode(SecurityUtils.getTenantCode());
        yqFormRule.setType("0");
        List<YqFormRule> list = yqFormRuleService.selectYqFormRuleList(yqFormRule);
        return list;
    }

    /**
     * 导出分单规则列表
     */
    @PreAuthorize("@ss.hasPermi('archive:RULE:export')")
    @Log(title = "分单规则", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, YqFormRule yqFormRule)
    {
        yqFormRule.setTenantCode(SecurityUtils.getTenantCode());
        List<YqFormRule> list = yqFormRuleService.selectYqFormRuleList(yqFormRule);
        ExcelUtil<YqFormRule> util = new ExcelUtil<YqFormRule>(YqFormRule.class);
        util.exportExcel(response, list, "分单规则数据");
    }

    /**
     * 获取分单规则详细信息
     */
    @PreAuthorize("@ss.hasPermi('archive:RULE:query')")
    @GetMapping(value = "/{ruleId}")
    public AjaxResult getInfo(@PathVariable("ruleId") String ruleId)
    {
        return success(yqFormRuleService.selectYqFormRuleByRuleId(ruleId));
    }

    /**
     * 新增分单规则
     */
    @PreAuthorize("@ss.hasPermi('archive:RULE:add')")
    @Log(title = "分单规则", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody YqFormRule yqFormRule)
    {
        yqFormRule.setTenantCode(SecurityUtils.getTenantCode());
        yqFormRule.setCONDITION(StringEscapeUtils.unescapeHtml4(yqFormRule.getCONDITION()==null?"":yqFormRule.getCONDITION()));
        yqFormRule.setRuleId(String.valueOf(SnowflakeIdGenerator.generateId()));
        int insertNum = yqFormRuleService.insertYqFormRule(yqFormRule);
        //TODO 添加的时候算出表达式并赋值给group数据
        String generatedExpression = null;
        if (yqFormRule.getGroupId()!=null){
            //子元素
            List<YqFormRule> yqFormRules = yqFormRuleService.selectYqFormRuleByGroupId(yqFormRule.getGroupId());
            StringBuilder stringBuilder = new StringBuilder();

            for (int i = 0; i < yqFormRules.size(); i++) {
                YqFormRule item = yqFormRules.get(i);
                if (i != 0) {
                    stringBuilder.append(" ").append(item.getColumnCondition()).append(" ");
                }
                String fieldName = item.getFieldName();
                String condition = item.getCONDITION();
                String dynamicValue = item.getDynamicValue();
                String staticValue = item.getStaticValue();
                String isStatic = item.getIsStatic();

                // 根据条件生成EL表达式
                String elExpression;
                if (condition.equals("equals")) {
                    elExpression = "${" + fieldName + " == '" + (isStatic.equals("1") ? staticValue : dynamicValue) + "'}";
                } else if (condition.equals("contains")) {
                    elExpression = "${fn:contains(" + fieldName + ", '" + (isStatic.equals("1") ? staticValue : dynamicValue) + "')}";
                } else if (condition.equals("startsWith")) {
                    elExpression = "${fn:startsWith(" + fieldName + ", '" + (isStatic.equals("1") ? staticValue : dynamicValue) + "')}";
                } else if (condition.equals("endsWith")) {
                    elExpression = "${fn:endsWith(" + fieldName + ", '" + (isStatic.equals("1") ? staticValue : dynamicValue) + "')}";
                } else if (condition.equals("notContains")) {
                    elExpression = "${not fn:contains(" + fieldName + ", '" + (isStatic.equals("1") ? staticValue : dynamicValue) + "')}";
                } else {
                    // 默认情况下使用原始的条件和值
                    elExpression = "${" + fieldName  + condition + (isStatic.equals("1") ? staticValue : dynamicValue) + "}";
                }

                stringBuilder.append(elExpression);
            }

            generatedExpression = stringBuilder.toString();
            System.out.println("=========================");
            System.out.println(generatedExpression);
            YqFormRule ruleGroup = new YqFormRule();
            ruleGroup.setRuleId(yqFormRule.getGroupId());
            ruleGroup.setColumnCondition(generatedExpression);
            ruleGroup.setTenantCode(SecurityUtils.getTenantCode());
            yqFormRuleService.updateYqFormRule(ruleGroup);
        }
        //yqFormRule.setRuleId(String.valueOf(SnowflakeIdGenerator.generateId()));
        return toAjax(insertNum);
    }

    @PreAuthorize("@ss.hasPermi('archive:RULE:add')")
    @Log(title = "分单规则", businessType = BusinessType.INSERT)
    @PostMapping("/batch")
    public AjaxResult addBatch(@RequestBody List<YqFormRule> yqFormRules) {
        if (yqFormRules.isEmpty()) {
            return AjaxResult.error("插入失败：没有任何数据");
        }
        String formId = null;

        //TODO 需要优化：大批量插入数据不能每次都进行规则拼接 对每个规则进行处理
        for (YqFormRule yqFormRule : yqFormRules) {
            formId = yqFormRule.getFormId()==null?formId:yqFormRule.getFormId();
            yqFormRule.setTenantCode(SecurityUtils.getTenantCode());
            //以是否为空判断是否修改操作
            if (yqFormRule.getRuleId()==null){
                yqFormRule.setRuleId(String.valueOf(SnowflakeIdGenerator.generateId()));

                int insertNum = yqFormRuleService.insertYqFormRule(yqFormRule);
            }else {
                //yqFormRule.setRuleId(String.valueOf(SnowflakeIdGenerator.generateId()));
                //以是否为空判断是否修改操作
                int insertNum = yqFormRuleService.updateYqFormRule(yqFormRule);

            }
        }
        boolean b = yqFormRuleService.updateColumnConditon(formId);

        return AjaxResult.success("Batch insert completed.");
    }


    /**
     * 修改分单规则
     */
    @PreAuthorize("@ss.hasPermi('archive:RULE:edit')")
    @Log(title = "分单规则", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody YqFormRule yqFormRule)
    {
        yqFormRule.setTenantCode(SecurityUtils.getTenantCode());
        return toAjax(yqFormRuleService.updateYqFormRule(yqFormRule));
    }

    /**
     * 删除分单规则
     */
    @PreAuthorize("@ss.hasPermi('archive:RULE:remove')")
    @Log(title = "分单规则", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ruleIds}")
    public AjaxResult remove(@PathVariable String[] ruleIds)
    {
        return toAjax(yqFormRuleService.deleteYqFormRuleByRuleIds(ruleIds));
    }

    /**
     * 删除分单规则
     */
    @PreAuthorize("@ss.hasPermi('archive:RULE:remove')")
    @Log(title = "分单规则", businessType = BusinessType.DELETE)
    @DeleteMapping("/deleteGroup/{ruleId}")
    public AjaxResult deleteGroup(@PathVariable String ruleId)
    {
        return toAjax(yqFormRuleService.deleteYqFormRuleByGroupRuleId(ruleId));
    }
    /**
     * 查询分单规则列表
     */
    /*@PreAuthorize("@ss.hasPermi('archive:RULE:list')")
    @GetMapping("/ruleList")
    public List<YqFormRule>  ruleList(YqFormRule yqFormRule)
    {
        //startPage();
        remoteCommonService.getf
        yqFormRule.setType("0");
        List<YqFormRule> list = yqFormRuleService.selectYqFormRuleList(yqFormRule);
        return list;
    }*/


}
